<template>
	<div>
		<!-- 面包屑导航 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
		  <el-breadcrumb-item :to="{ path: '/welcom' }">首页</el-breadcrumb-item>
		  <el-breadcrumb-item>用户管理</el-breadcrumb-item>
		  <el-breadcrumb-item>用户列表</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 用户列表区域 -->
		<el-card class="box-card">
			<!-- 搜索框 -->
			<el-row :gutter="20">
			  <el-col :span="9">
				<div class="grid-content bg-purple">	
					<el-input v-model="queryInfo.query"  placeholder="请输入姓名" prefix-icon="el-icon-search">
						<el-button slot='append' @click='searchUser'>搜 索</el-button>
					</el-input>
				</div>
			  </el-col>
				<!-- 添加用户按钮 -->
			  <el-col :span="8">
				  <div class="grid-content bg-purple">
					<el-button type="primary" class="button-circle" @click='handleOpenDialog'>添加用户</el-button>
					<!-- 添加用户对话框 -->
					<el-dialog
					  title="添加用户"
					  :visible.sync="centerDialogVisible"
					  width="30%"
					  center>
					  <!-- 添加用户填写信息表单 -->
					  <el-form ref="addUserForm" :model="addUserForm" :rules="addUserFormRules" label-width="60px">
					    <el-form-item label="姓名" prop="username" >
					      <el-input v-model="addUserForm.username"></el-input>
					    </el-form-item>
						<el-form-item label="密码" prop="password" >
						  <el-input v-model="addUserForm.password"></el-input>
						</el-form-item>
						<el-form-item label="邮箱" prop="email">
						  <el-input v-model="addUserForm.email"></el-input>
						</el-form-item>
						<el-form-item label="电话" prop="mobile">
						  <el-input type="mobile" v-model="addUserForm.mobile"></el-input>
						</el-form-item>
					  </el-form>
						<!-- 页脚按钮区 -->
					  <span slot="footer" class="dialog-footer">
					    <el-button size="small" @click="centerDialogVisible = false">取 消</el-button>
					    <el-button size="small" type="primary" @click="submitForm('addUserForm')">确 定</el-button>
					  </span>
					</el-dialog>
			      </div>
			  </el-col>
			</el-row>
			<template>
			<!-- 用户信息表单 -->
			  <el-table
			    v-loading="loading"
			    :data="userList"
				border
				stripe
			    style="width: 100%;">
				 <el-table-column  type="index" label="#"  :index="indexMethod"></el-table-column>
			    <el-table-column prop="username" label="姓名">
			    </el-table-column>
			    <el-table-column  prop="email" label="邮箱"></el-table-column>
			    <el-table-column  prop="mobile"  label="电话">
			    </el-table-column>
				<el-table-column  prop="role_name"  label="角色">
				</el-table-column>
				<el-table-column  prop="mg_state"  label="状态">
					<!-- 作用域插槽 -->
					 <template slot-scope="scope">
					        <el-switch
					          v-model="scope.row.mg_state"
					          active-color="#13ce66"
					          inactive-color=""
							  @change="handleStateChange(scope.row)">
					        </el-switch>
					 </template>
				</el-table-column>
				<!-- 表单操作区域 -->
				<el-table-column label="操作">
					<template slot-scope="scope">
						<el-tooltip content="修改信息"  :enterable='false' placement="top">
						   <el-button type="primary" @click='UserDialog(scope.row)' icon="el-icon-edit" size="mini" circle></el-button>
						</el-tooltip>
						<el-tooltip content="删除用户"  :enterable='false' placement="top">
						   <el-button type="danger" @click='deleteUser(scope.row.id)' icon="el-icon-delete" size="mini" circle></el-button>
						</el-tooltip>
						<el-tooltip content="分配角色"  :enterable='false' placement="top">
						   <el-button type="warning"  @click='setRoleDialog(scope.row)' icon="el-icon-setting" size="mini" circle></el-button>
						</el-tooltip>
						<!-- 分配角色对话框 -->
						<el-dialog
						  title="分配角色"
						  :visible.sync="setRoleDialogVisible"
						  width="30%"
						  >
						  <div>
							  <p>用户名： {{settingUser.username}}</p>
							  <p>当前角色： {{rolename}}<el-dropdown>
							    <el-button type="primary"  size="mini">
							      分配角色<i class="el-icon-arrow-down el-icon--right"></i>
							    </el-button>
							    <el-dropdown-menu slot="dropdown">
										 <div  v-for="item in rolesList" :key="item.id"  @click="handleChangeRole(item)"><el-dropdown-item >{{item.roleName}}</el-dropdown-item></div>	     
							    </el-dropdown-menu>
							  </el-dropdown></p>
							  
						  </div>
						  <span slot="footer" class="dialog-footer">
						    <el-button @click="setRoleDialogVisible = false">取 消</el-button>
						    <el-button type="primary" @click="submitRoleName">确 定</el-button>
						  </span>
						</el-dialog>
						<!-- 修改用户对话框 -->
						<el-dialog
						  title="修改用户"
						  :visible.sync="alterUserDialogVisible"
						  width="40%"
						  center>
						  <el-form ref="alterUserForm" :model="alterUserForm" label-width="60px" :rules="addUserFormRules">
							  <el-form-item label="用户名">
								   <el-input v-model="alterUserForm.username"  disabled></el-input>
							  </el-form-item>
							  <el-form-item  label="电 话" prop="mobile">
							  		<el-input v-model="alterUserForm.mobile"></el-input>
							  </el-form-item>
							  <el-form-item  label="邮 箱" prop="email">
							  		<el-input v-model="alterUserForm.email"></el-input>
							  </el-form-item>
						  </el-form>
							<!-- 页脚按钮区 -->
						  <span slot="footer" class="dialog-footer">
						    <el-button size="small" @click="alterUserDialogVisible = false">取 消</el-button>
						    <el-button size="small" type="primary" @click="submitalterForm('alterUserForm')">确 定</el-button>
						  </span>
						</el-dialog>
					</template>
				</el-table-column>
			  </el-table>
			  <!-- 分页 -->
			   <el-pagination
			        @size-change="handleSizeChange"
			        @current-change="handleCurrentChange"
			        :current-page="queryInfo.pagenum"
			        :page-sizes="[10, 15, 20]"
			        :page-size="queryInfo.pagesize"
			        layout="total, sizes, prev, pager, next, jumper"
			        :total="total"
					background>
			      </el-pagination>
			</template>
		</el-card>
	</div>
</template>

<script>
	export default{

		created() {
			this.getUserList()
		},
		data() {
		      return {
		        loading: true,
				queryInfo:{
					query:'',
					pagenum:1,
					pagesize:10
				},
				addUserForm:{
					username:'',
					password:'',
					email:'',
					mobile:''
				},
				alterUserForm:{},
				total:0,
				userList:[], //所以用户列表
				settingUser:[],//要修改角色的用户
				rolesList:[],//所有角色列表
				rolename:'',
				roleid:'',
				centerDialogVisible:false,
				alterUserDialogVisible:false,
				setRoleDialogVisible:false,
				//添加用户表单验证
				addUserFormRules:{
					username: [
					  { required: true, message: '请输入用户名', trigger: 'blur' },
					  { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
					],
					password: [
					  { required: true, message: '请输入密码', trigger: 'blur' },
					  { min: 5, max: 12, message: '长度在 5 到 12 个字符', trigger: 'blur' }
					],
					email:[
					  { pattern:/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/, message: '请输入正确的邮箱号', trigger: 'blur' }
					],
					mobile:[ { pattern:/^\d{11}$/, message: '请输入正确的手机号' } ]
				      }
		      };
		    },
		methods:{

			//获取用户信息列表
		  async	getUserList(){
			    
				const { data:res } = await this.$http.get('users',{ params:this.queryInfo })
				 console.log(res)
				 if(res.meta.status !== 200)
				 return this.$message.error(res.meta.msg)
				 this.userList = res.data.users
				 this.loading = false
				 this.total = res.data.total
				 // var that = this
				 // window.setTimeout(function(){ that.loading = false },750)
				 //console.log(this.userList)
				 
			},
			//页表索引值
			 indexMethod(index) {
			        return index+1;
			      },
			//改变页码数
			handleCurrentChange(newPage){
				console.log(newPage)
				this.queryInfo.pagenum = newPage
			this.getUserList()
			},
			//改变页面容量
			handleSizeChange(newSize){
				console.log(newSize)
				this.queryInfo.pagesize = newSize
				this.getUserList()
			},
			//按用户名关键字查询用户
			async searchUser(){
			    const { data:res } = await this.$http.get('users',{ params:this.queryInfo})
				if(res.meta.status !== 200)
				return this.$message.error(res.meta.msg)
				this.userList = res.data.users
				this.loading = false
				this.total = res.data.total
			},
			//改变用户状态
			async handleStateChange(state){
				console.log(state)
				const  { data:res }  =await this.$http.put('users/'+state.id+'/state/'+state.mg_state)
				if( res.meta.status === 200	)
				return this.$message.success(res.meta.msg)
				else
				{
					state.mg_state = !state.mg_state
					this.$message.error('设置失败')
				}
			},
			//打开添加用户对话框
			handleOpenDialog(){
				this.centerDialogVisible = true
			},
			//提交新增用户表单
			 submitForm(addUserForm){
				this.$refs[addUserForm].validate( async (valid) => {
          if (valid) {
            const { data:res } = await this.$http.post('users',this.addUserForm)
			console.log(res)
			if( res.meta.status !== 201 )
			{ return this.$message.error(res.meta.msg) }
			
			this.$message.success(res.meta.msg)
			this.centerDialogVisible = false
			this.getUserList()
          } 
        });
			},
			//查询要修改的用户信息
			async UserDialog(userData){
				console.log(userData)
				this.alterUserDialogVisible = true
			  const {data:res} = await this.$http.get('users/'+userData.id)
			    console.log(res)
				if( res.meta.status !==200 )
				return this.$message.error(res.meta.msg)
				this.alterUserForm = res.data
				console.log(this.alterUserForm.id)
			},
			//提交修改表单
			submitalterForm(alterUserForm){
				console.log(this.alterUserForm.mobile)
				this.$refs[alterUserForm].validate( async (valid) => {
				  if (valid) {
				    const { data:res } = await this.$http.put('users/'+this.alterUserForm.id,{email:this.alterUserForm.email,mobile:this.alterUserForm.mobile})
					console.log(res)
					if( res.meta.status !== 200 )
					{ return this.$message.error(res.meta.msg) }
					
					this.$message.success(res.meta.msg)
					this.alterUserDialogVisible = false
					this.getUserList()
				  } 
				});
			},
		
		//删除用户
		 deleteUser(userId){
			        this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
			          confirmButtonText: '确定',
			          cancelButtonText: '取消',
			          type: 'warning'
			        }).then(async() => {
					 const {data:res} = await this.$http.delete('users/'+userId)
					 if( res.meta.status !== 200 )
					 return res.meta.msg 
			          this.$message({
			            type: 'success',
			            message: '删除成功!'
			          });
					  this.getUserList()
			        }).catch(() => {
			          this.$message({
			            type: 'info',
			            message: '已取消删除'
			          });          
			        });
			      }
			,
			async setRoleDialog(user){
				this.settingUser = user
				this.setRoleDialogVisible = true
				this.rolename = user.role_name
				console.log(user)
				
				const { data:res } = await this.$http.get('roles')
				console.log(res)
				if( res.meta.status !== 200 )
				return this.$message.error('获取角色列表失败！')
				
				this.rolesList = res.data
				
			},
			handleChangeRole(role){
				console.log(role)
				this.rolename = role.roleName
				this.roleid = role.id
			},
			async submitRoleName(){
				console.log(this.settingUser.id)
				console.log(this.roleid)
                const { data:res } = await this.$http.put('users/'+this.settingUser.id+'/role/',
				{
					rid:this.roleid
				})
				console.log(res)
				if( res.meta.status !== 200 )
				return this.$message.error(res.meta.msg)
				
				this.$message.success('设置成功')
				this.getUserList()
				this.setRoleDialogVisible = false
			}
			}	  
	}
</script>

<style lang="less" scoped>



</style>
